import axios from 'axios';
import router from '@/router';
import { ElMessage } from 'element-plus';
import { ContentTypeEnum, RequestEnum, ResultEnum } from '@/enums/httpEnum';
import { useAuthStore } from '@/stores/modules/auth';

/**通用请求参数处理 */
export const request = (axiosInstance) => (method, url, data, config = { headers: {} }) => {
  const authStore = useAuthStore()

  /* 设置token请求头 */
  /* if(authStore.base_auth_token) {
    config.headers.token = authStore.base_auth_token
  } */

  /* 请求参数 */
  let requestData = {};
  if (data) {
    requestData = data;
  }

  const option = { method, url }
  method == RequestEnum.GET ? option.params = requestData : option.data = requestData

  return axiosInstance({ ...option, ...config });
}

/**
 * 默认公用配置
 */
const defaultOptions = {
  /**
   * 请求钩子
   */
  requestHook: config => {
    return config
  },
  /**
   * 响应数据钩子
   */
  responseHook: (response) => {
    return response.data
  },
  /**
   * 响应错误钩子
   */
  responseErrorHook: error => {
    Promise.reject(error)}
}

/**
 * 生成通用请求工具
 */
export default (options) => {
  const serviceOptions = { ...defaultOptions, ...options }

  const service = axios.create({
    baseURL: options.baseUrl,
    timeout: 15 * 1000
  });

  /**请求拦截器 */
  service.interceptors.request.use(serviceOptions.requestHook);

  /**响应拦截器 */
  service.interceptors.response.use(
    serviceOptions.responseHook,
    serviceOptions.responseErrorHook
  );

  /**请求方法封装 */
  const $GET = (url, data, config) => request(service)(RequestEnum.GET, url, data, config);

  const $POST = (url, data, config) => request(service)(RequestEnum.POST, url, data, config);

  const $PUT = (url, data, config) => request(service)(RequestEnum.PUT, url, data, config);

  const $DELETE = (url, data, config) => request(service)(RequestEnum.DELETE, url, data, config);

  return { axiosIns: service, $GET, $POST, $PUT, $DELETE }
}